package com.zzx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.config.UserContext;
import com.zzx.entity.TUserMenu;
import com.zzx.mapper.TUserMenuMapper;
import com.zzx.service.TUserMenuService;
import com.zzx.utils.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author CD
 * @description 针对表【t_employee_menu】的数据库操作Service实现
 * @createDate 2024-12-16 15:30:48
 */
@Service
public class TUserMenuServiceImpl extends ServiceImpl<TUserMenuMapper, TUserMenu>
        implements TUserMenuService {
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TUserMenu param) {

        if (ObjectUtils.isEmpty(param.getUserMenuId())) {
            param.setUserMenuId(IdUtil.getSnowflakeNextId());
        } else {
            EntityUtils.mergeNonNullProperties(this.getBaseMapper().selectById(param.getUserMenuId()), param);
        }
        this.saveOrUpdate(param);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addList(List<TUserMenu> param) {
        param.forEach(e -> {
            if (ObjectUtils.isEmpty(e.getUserMenuId())) {
                e.setUserMenuId(IdUtil.getSnowflakeNextId());
            }
        });
        this.saveOrUpdateBatch(param);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(TUserMenu param) {

        if (!ObjectUtils.isEmpty(param.getIds())) {
            this.removeBatchByIds(param.getIds());
        }
        if (!ObjectUtils.isEmpty(param.getUserId())) {
            this.removeById(param.getUserId());
        }
        if (!ObjectUtils.isEmpty(param.getUserMenuId())) {
            this.removeById(param.getUserMenuId());
        }
    }

    @Override
    public List<TUserMenu> selectBy(TUserMenu param) {
        LambdaQueryWrapper<TUserMenu> wrapper = new LambdaQueryWrapper<>(TUserMenu.class);
        if (!ObjectUtils.isEmpty(param.getUserId())) {
            wrapper.eq(TUserMenu::getUserId, param.getUserId());
        }
        wrapper.eq(TUserMenu::getCompanyId, UserContext.getCompanyId());
        List<Long> collect = this.getBaseMapper().selectList(wrapper).stream().map(e -> e.getMenuId()).collect(Collectors.toList());
        if (collect.isEmpty()) {
            throw new RuntimeException("无菜单权限");
        } else {
            return this.getBaseMapper().selectBy(collect);
        }
    }
}




